import settings from "../utils/settings";
import { location } from "../utils/getLocation";
import { MessageID, Vec3iToVec3, getEntityHP, getPlayerPos } from "../utils/utils";
import { Vec3 } from "../utils/vec3";
import legendarySeaCreatureSettings from "../utils/legendarySeaCreatureSettings";
import petmanager from "../utils/petmanager";


export function fishing() {}

//旧配置迁移
if (FileLib.exists("./config/ChatTriggers/modules/BabyzombieAddons/config/fishingSetting.json")) try {
    let oldLegendarySeaCreatureSettings = JSON.parse(FileLib.read("./config/ChatTriggers/modules/BabyzombieAddons/config/fishingSetting.json"));
    for (let sc in oldLegendarySeaCreatureSettings) {
        for (let key in oldLegendarySeaCreatureSettings[sc]) {
            if (legendarySeaCreatureSettings[sc + "_" + key] != undefined) 
                legendarySeaCreatureSettings[sc + "_" + key] = (key == "volume" || key == "pitch" ? oldLegendarySeaCreatureSettings[sc][key] * 10 : oldLegendarySeaCreatureSettings[sc][key]);
        }
    }
    FileLib.delete("./config/ChatTriggers/modules/BabyzombieAddons/config/fishingSetting.json");
} catch (error) {}


//传奇海怪提醒
const seaCreatureMessage = new Map()
    //////////垃圾池钓//////////
    .set("A long snout breaks the surface of the water. It's an Alligator!","Alligator")
    .set("A massive Titanoboa surfaces. It's body stretches as far as the eye can see.","Titanoboa")
    //////////热门钓鱼点钓///////
    .set("A garish set of tentacles arise. It's a Blue Ringed Octopus!","Blue Ringed Octopus")
    //.set("A Fiery Scuttler inconspicuously waddles up to you, friends in tow.","Fiery Scuttler") 岩浆
    .set("The water bubbles and froths. A massive form emerges- you have disturbed the Wiki Tiki! You shall pay the price.","Wiki Tiki")

    ////////// 一般水钓 //////////
    .set("The Water Hydra has come to test your strength.", "Water_Hydra")
    .set("The Sea Emperor arises from the depths.", "The_Sea_Emperor")
    .set("An Abyssal Miner breaks out of the water!", "Zombie_Miner")
    ////////// 岩浆钓 //////////
    .set("You hear a massive rumble as Thunder emerges.", "Thunder")
    .set("You have angered a legendary creature... Lord Jawbus has arrived.", "Lord_Jawbus")
    .set("A Fiery Scuttler inconspicuously waddles up to you, friends in tow.","Fiery Scuttler")
    .set("The sky darkens and the air thickens. The end times are upon us: Ragnarok is here.","Ragnarok")
    ////////// 万圣节水钓 //////////
    .set("The spirit of a long lost Phantom Fisher has come to haunt you.", "Phantom_Fisherman")
    .set("This can't be! The manifestation of death himself!", "Grim_Reaper")
    ////////// 冬岛水钓 //////////
    .set("What is this creature!?", "Yeti")
    .set("A Reindrake forms from the depths.", "Reindrake")
    ////////// 钓鱼节水钓 //////////
    .set("Hide no longer, a Great White Shark has tracked your scent and thirsts for your blood!", "Great_White_Shark");

register("chat", (message) => {
    if(!location.inSkyblock) return;
    let sc = seaCreatureMessage.get(message);
    if(!sc) return;
    if(legendarySeaCreatureSettings[sc + "_showTitle"]) Client.showTitle(legendarySeaCreatureSettings[sc + "_title"],legendarySeaCreatureSettings[sc + "_subTitle"],5,80,15);
    if(legendarySeaCreatureSettings[sc + "_playSound"]) setTimeout(() => { World.playSound(legendarySeaCreatureSettings[sc + "_sound"],legendarySeaCreatureSettings[sc + "_volume"] / 10,legendarySeaCreatureSettings[sc + "_pitch"] / 10); }, 100);
    if(legendarySeaCreatureSettings[sc + "_sendMessage"]) ChatLib.command("pc " + legendarySeaCreatureSettings[sc + "_message"].replace("%coords%", Vec3iToVec3(getPlayerPos().toVec3i()).toString()));
}).setCriteria("${message}")


//地狱 火山 蒸汽 锁高度
register("spawnParticle", (particle,type,event) => {
    if(!settings.volcanoSteam || !location.inSkyblock || location.island != "Crimson Isle" || location.location != "Blazing Volcano") return;
    if(!Player.getHeldItem() || Player.getHeldItem().getID() != 346) return;
    if(["SMOKE_NORMAL","CLOUD","REDSTONE","SPELL_MOB_AMBIENT","LAVA"].indexOf(type.toString()) == -1) return;
    let pos = Vec3iToVec3(particle.getPos());
    if(pos.isIn(new Vec3i(-422,117,-840),new Vec3i(-322,126,-740))) {
        particle.setPosition(pos.x,116,pos.z);
    }
})

//地狱抛竿不到能上slug的时间不给收杆
function getSlugPetLevel() {
    if(!petmanager.getPet() || petmanager.getPet().getName() !== "SLUG") return 0;
    return petmanager.getPet().getLevel();
}
let hook = undefined; let hookTimestamp = 0; let goldenFish = false;
register("tick", () => {
    if(hook && hook.isDead()) { hook = undefined; hookTimestamp = 0; };
    if(hook) return;
    if(!settings.hookLocked || location.island != "Crimson Isle") return;
    let entity = World.getAllEntitiesOfType(net.minecraft.entity.projectile.EntityFishHook).filter(e => e && e.getEntity().field_146042_b && e.getEntity().field_146042_b == Player.getPlayer());  //e.getEntity().angler
    if(entity.length) {
        hook = entity[0]; hookTimestamp = Date.now();
    }
})
register("playerInteract", (action,pos,event) => {
    if(settings.hookLocked && !goldenFish && hookTimestamp && Date.now() - hookTimestamp < (20 * 1000 - getSlugPetLevel() * 100)) cancel(event);
})
register("soundPlay", (pos,name,vol,pitch,cate,event) => {
    if(settings.hookLocked && !goldenFish && (name == "note.pling" || name == "game.player.swim.splash") && hookTimestamp && Date.now() - hookTimestamp < (20 * 1000 - getSlugPetLevel() * 100)) cancel(event);
})
register("worldLoad",()=>{ hook = undefined; hookTimestamp = 0; goldenFish = false;})
register("chat", (message) => {
    if(!location.inSkyblock) return;
    switch (message) {
        case "The Golden Fish is weak!":
            goldenFish = true;
            Client.showTitle("","§aThe Golden Fish is weak!",0,60,20);
            World.playSound("note.pling",1,1);
            setTimeout(() => {
                World.playSound("note.pling",1,1);
            }, 500);
            break;
        case "The Golden Fish swims back beneath the lava...":
            goldenFish = false;
            break;
        default:
            if(message.startsWith("TROPHY FISH! You caught a Golden Fish ") && message.endsWith(".")) {
                goldenFish = false;
            }
            break;
    }
}).setCriteria("${message}")

//隐藏看不见但又挡右键的别人的金鱼
register("attackEntity", (entity,event) => {
    if(!settings.KillInvisibleGoldenFish || !location.inSkyblock || location.island != "Crimson Isle") return;
    try {
        if(Player.getHeldItem() == null || Player.getHeldItem().getID() != 346) return;
        if(entity.getClassName() != "EntityArmorStand" || !(entity.getName() == "" || entity.getName() == "盔甲架")) return;
        for (let i = 0; i < 5; i++) {
            if(entity.getEntity().func_71124_b(i)) return;
        }
        if(entity.getEntity().func_82150_aj())  //entity.isInvisible()
            entity.getEntity().func_70106_y();  //entity.setDead()
    } catch (error) {}
})

//显示冬岛龙的血量
register("renderBossHealth", () => {
    if(!settings.ShowReindrakeHP || !location.inSkyblock || location.island != "Jerry's Workshop") return;
    World.getAllEntitiesOfType(net.minecraft.entity.boss.EntityDragon).filter(e => e.getName().removeFormatting().startsWith("Reindrake")).forEach(e => {
        let hp = getEntityHP(e);
        e.getEntity().func_96094_a("§4Reindrake §r" + (hp.hp/hp.maxhp > 0.5 ? "§a" : "§e") + parseInt(hp.hp) + "§r/§a" + parseInt(hp.maxhp) + "§c❤");  //setCustomNameTag
    })
})